import heapq


def top_k(nums, k):
    # 将前 k 个元素建立最小堆
    heap = nums[:k]
    heapq.heapify(heap)

    # 遍历剩下的元素，如果比堆顶元素大，则弹出堆顶元素，将该元素插入堆中
    for i in range(k, len(nums)):
        if nums[i] > heap[0]:
            heapq.heappop(heap)
            heapq.heappush(heap, nums[i])

    # 将堆中的元素按照从大到小的顺序排列，并返回前 k 个元素
    return sorted(heap, reverse=True)


# 示例
nums = [3, 4, 1, 5, 2, 6, 9, 8, 7]
k = 3
result = top_k(nums, k)
print(result)  # [9, 8, 7]
